from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings

from goods.models import SKUImage, SKU
from meiduo_admin.utils import PageNum
from meiduo_admin.serializers.image import ImagesSerializer, SKUSerializer
from celery_tasks.static_files.tasks import generate_static_sku_detail_html


class ImagesView(ModelViewSet):
    queryset = SKUImage.objects.all()
    pagination_class = PageNum
    serializer_class = ImagesSerializer

    permission_classes = [IsAdminUser]

    def simple(self, request):
        skus = SKU.objects.all()
        ser = SKUSerializer(skus, many=True)
        return Response(ser.data)

    def create(self, request, *args, **kwargs):
        data = request.data
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        fc = Fdfs_client(settings.FDFS_CONF_PATH)
        img_file = request.FILES.get('image')
        ret = fc.upload_by_buffer(img_file.read())

        if ret['Status'] != 'Upload successed.':
            return Response('Error: Image Upload Failure')

        img = SKUImage.objects.create(sku=serializer.validated_data['sku'], image=ret['Remote file_id'])
        
        generate_static_sku_detail_html.delay(img.sku_id)

        return Response(
            {
                'id': img.id,
                'sku_id': img.sku_id,
                'image': img.image.url
            }, status=201
        )
    